import React from 'react';
import { HttpCode } from '@/utils/contacts';
import { getTreeByCodes } from '@/utils';
import { queryMarketList } from '../services';

export default (menuCode, pageType) => {
  // 子页面不需要数据权限
  if (pageType === 'child') return {};
  const [error, setError] = React.useState('');
  const [loading, setLoading] = React.useState(true);
  const [powerData, setPowerData] = React.useState([]);
  const [stationMap, setStationMap] = React.useState({});

  React.useEffect(() => {
    fetchPower();
  }, []);

  const fetchPower = async () => {
    let res = await queryMarketList(menuCode);
    let error = '';
    let list = [];
    let stationMap = {};
    if (res?.statusCode === HttpCode.SUCCESS) {
      const { treeOptions } = getTreeByCodes(['market', 'group', 'station'], res.json);
      list = treeOptions;
      list.map((x) => {
        x.value = x.provinceId;
        x.children.map((y) => {
          y.children.map((z) => {
            stationMap[z.value] = z.label;
          });
        });
      });
    } else {
      error = res?.message;
    }
    setError(error);
    setPowerData(list);
    setLoading(false);
    setStationMap(stationMap);
  };

  return {
    error,
    loading,
    powerData,
    stationMap,
  };
};
